<template>
  <div 
    id="floating-button" 
    :style="{
      left: `${positionX}px`,
      top: `${positionY}px`,
      transition: isDragging ? 'none' : transitionStyle
    }"
  >
    <div 
      class="button-content"
      @mousedown="startDrag"
      @touchstart="startDrag"
      @mouseup="handleMouseUp"
      @touchend="handleMouseUp"
    >
      <slot>悬浮按钮</slot>
    </div>
  </div>
</template>
<script>
export default {
  name: 'FloatingButton',
  props: {
    onClick: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      positionX: window.innerWidth - 80,
      positionY: window.innerHeight / 2 - 40,
      startX: 0,
      startY: 0,
      originX: 0,
      originY: 0,
      isDragging: false,
      isPressed: false,
      buttonWidth: 60,
      buttonHeight: 60,
      margin: 10,
      transitionStyle: 'left 0.3s ease, top 0.3s ease',
      moveHandler: null,
      clickThreshold: 5, // 超过5px则视为拖拽
      animationFrameId: null
    }
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    this.handleResize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.removeGlobalListeners();
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
  },
  methods: {
    handleResize() {
      this.positionX = Math.max(this.margin, Math.min(this.positionX, window.innerWidth - this.buttonWidth - this.margin));
      this.positionY = Math.max(this.margin, Math.min(this.positionY, window.innerHeight - this.buttonHeight - this.margin));
    },
    startDrag(e) {
      e.preventDefault();
      this.isPressed = true;
      this.isDragging = false;
      
      // 记录初始位置
      const point = e.type === 'mousedown' ? e : e.touches[0];
      this.startX = point.clientX;
      this.startY = point.clientY;
      this.originX = point.clientX;
      this.originY = point.clientY;
      
      // 添加全局移动监听
      this.moveHandler = this.throttle(this.onDrag, 10);
      document.addEventListener('mousemove', this.moveHandler);
      document.addEventListener('touchmove', this.moveHandler);
    },
    onDrag(e) {
      if (!this.isPressed) return;
      
      const point = e.type === 'mousemove' ? e : e.touches[0];
      if (!point) return;
      
      // 计算移动距离
      const deltaX = point.clientX - this.startX;
      const deltaY = point.clientY - this.startY;
      const totalDeltaX = Math.abs(point.clientX - this.originX);
      const totalDeltaY = Math.abs(point.clientY - this.originY);
      
      // 判断是否超过点击阈值
      if (totalDeltaX > this.clickThreshold || totalDeltaY > this.clickThreshold) {
        this.isDragging = true;
      }
      
      // 如果是拖拽状态，更新位置
      if (this.isDragging) {
        if (this.animationFrameId) {
          cancelAnimationFrame(this.animationFrameId);
        }
        
        this.animationFrameId = requestAnimationFrame(() => {
          this.positionX += deltaX;
          this.positionY += deltaY;
          
          // 限制在可视区域内
          this.positionX = Math.max(this.margin, Math.min(this.positionX, window.innerWidth - this.buttonWidth - this.margin));
          this.positionY = Math.max(this.margin, Math.min(this.positionY, window.innerHeight - this.buttonHeight - this.margin));
          
          // 更新起始点
          this.startX = point.clientX;
          this.startY = point.clientY;
        });
      }
    },
    handleMouseUp(e) {
      if (!this.isPressed) return;
      
      e.preventDefault();
      this.isPressed = false;
      
      // 移除全局监听
      this.removeGlobalListeners();
      
      // 清除动画帧
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }
      
      // 处理拖拽结束后的吸附
      if (this.isDragging) {
        const middleX = window.innerWidth / 2;
        this.positionX = this.positionX < middleX ? this.margin : window.innerWidth - this.buttonWidth - this.margin;
        this.isDragging = false;
      } 
      // 处理点击事件（未拖拽且移动距离小于阈值）
      else {
        const point = e.type === 'mouseup' ? e : e.changedTouches[0];
        const totalDeltaX = Math.abs(point.clientX - this.originX);
        const totalDeltaY = Math.abs(point.clientY - this.originY);
        
        if (totalDeltaX <= this.clickThreshold && totalDeltaY <= this.clickThreshold) {
          console.log('点击事件触发');
          this.onClick(); // 触发点击回调
        }
      }
    },
    removeGlobalListeners() {
      if (this.moveHandler) {
        document.removeEventListener('mousemove', this.moveHandler);
        document.removeEventListener('touchmove', this.moveHandler);
        this.moveHandler = null;
      }
    },
    throttle(fn, delay) {
      let lastCall = 0;
      return function(...args) {
        const now = Date.now();
        if (now - lastCall < delay) {
          return;
        }
        lastCall = now;
        return fn.apply(this, args);
      }
    }
  }
}
</script>
<style scoped>
#floating-button {
  position: fixed;
  z-index: 9999;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  user-select: none;
  -webkit-user-select: none;
}

.button-content {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  touch-action: none;
  transition: transform 0.15s ease;
}

.button-content:active {
  transform: scale(0.95);
}
</style>
